const serviceSql=require('../service/service')
const {v4}=require('uuid')
const {RECHARGE_ERROR}=require('../error/errorType')

class rechargeController{
    async recharge(ctx,next){
        const codeStatus=ctx.codeStatus
        const amount=ctx.amount
        const {id}=ctx.tokenInfo
        const orderNo=(()=>v4())()
        let {affectedRows:rechargeRows} = await serviceSql.recharge(amount,orderNo,id,0)
        if(!rechargeRows){
            return ctx.app.emit('error',new Error(RECHARGE_ERROR),ctx)
        }
        let [result]=await serviceSql.user(id)
        const {amount:amountOld}=result
        let {affectedRows:updataUserRows} = await serviceSql.updataUser(amount+Number(amountOld),id)
        if(!updataUserRows){
            return ctx.app.emit('error',new Error(RECHARGE_ERROR),ctx)
        }
        
        ctx.mesg=codeStatus==1?'兑换成功':'充值成功'
        ctx.body=[]
        await next()
    }
}

module.exports=new rechargeController()